package com.xoa.service.guideGoal.impl;

import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.guideGoal.GuideGoalTypeMapper;
import com.xoa.util.guideGoal.GuideGoalTreeUtil;
import com.xoa.model.guideGoal.GuideGoalType;
import com.xoa.service.guideGoal.GuideGoalTypeService;
import com.xoa.model.users.Users;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.treeUtil.CheckTree;
import com.xoa.util.treeUtil.TreeGirdNode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by gsb on 2017/7/28.
 */
@Service
public class GuideGoalTypeServiceImpl implements GuideGoalTypeService {

    @Resource
    GuideGoalTypeMapper guideGoalTypeMapper;

    @Resource
    UsersMapper usersMapper;
    @Resource
    DepartmentMapper departmentMapper;
    @Resource
    UserPrivMapper userPrivMapper;
    @Override
    public  ToJson<GuideGoalType> getSupervisionTypeDetail(HttpServletRequest request, Integer sid){
        ToJson<GuideGoalType> toJson=new ToJson<GuideGoalType>(1, "error");
        try{
            GuideGoalType guideGoalType = guideGoalTypeMapper.getSupervisionTypeDetail(sid);
            if(guideGoalType !=null){
            	String range=this.checkAll(guideGoalType.getUserId());
            	 String[] checkStrings=range.split("\\|");
            	 String[] checkStringOr=(guideGoalType.getUserId()==null?"": guideGoalType.getUserId()).split("\\|");
    		     //数组长度为1时 说明此时角色和用户Id权限为空
    		   if(checkStrings.length==1){
    		   	if(checkStringOr.length>0){
					guideGoalType.setDeptName(checkStrings[0]);
					guideGoalType.setDeptId(checkStringOr[0]);
					guideGoalType.setUserPrivName("");
					guideGoalType.setUserPrivId("");
					guideGoalType.setUserName("");
					guideGoalType.setUserId("");

				}

    		   }
    		     //数组长度为2时 说明此时角色和用户Id权限为空
    		   if(checkStrings.length==2){
				   if(checkStringOr.length>0) {
					   guideGoalType.setDeptName(checkStrings[0]);
					   guideGoalType.setDeptId(checkStringOr[0]);
					   guideGoalType.setUserPrivName(checkStrings[1]);
					   guideGoalType.setUserPrivId(checkStringOr[1]);
					   guideGoalType.setUserName("");
					   guideGoalType.setUserId("");
				   }
    		   }
    		     //数组长度为3时 说明此时部门、角色和用户Id权限都不为空
    		   if(checkStrings.length==3){
				   if(checkStringOr.length>0) {
					   guideGoalType.setDeptName(checkStrings[0]);
					   guideGoalType.setDeptId(checkStringOr[0]);
					   guideGoalType.setUserPrivName(checkStrings[1]);
					   guideGoalType.setUserPrivId(checkStringOr[1]);
					   guideGoalType.setUserName(checkStrings[2]);
					   guideGoalType.setUserId(checkStringOr[2]);
				   }
    		   }
				//数组长度为3时 说明此时部门、角色和用户Id权限都不为空
				if(checkStrings.length==4){
					if(checkStringOr.length>0) {
						guideGoalType.setDeptName(checkStrings[0]);
						guideGoalType.setDeptId(checkStringOr[0]);
						guideGoalType.setUserPrivName(checkStrings[1]);
						guideGoalType.setUserPrivId(checkStringOr[1]);
						guideGoalType.setUserName(checkStrings[3]);
						guideGoalType.setUserId(checkStringOr[2]);
					}
				}
                toJson.setObject(guideGoalType);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else {
                toJson.setMsg("没有详细信息");
                toJson.setFlag(0);
            }
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return  toJson;
    }

    @Override
    public ToJson<GuideGoalType> updateSupervisionType(HttpServletRequest request, GuideGoalType guideGoalType){
        ToJson<GuideGoalType> toJson=new ToJson<GuideGoalType>(1, "error");
        try{
           /* Users users=new Users();
            //users.setUid(supervisionType.getUid());
            users.setDeptId(Integer.valueOf(request.getParameter( "deptId"))==null?0:Integer.valueOf(request.getParameter( "deptId")));
            users.setUserName(request.getParameter("userName")==null?"":request.getParameter("userName"));
            users.setDeptName(request.getParameter("deptName")==null?"":request.getParameter("deptName"));
            users.setUserPrivName(request.getParameter("userPrivName")==null?"":request.getParameter("userPrivName"));*/
           if(guideGoalType.getParentId()==-1){
           	guideGoalType.setParentId(0);
		   }
           int a= guideGoalTypeMapper.updateSupervisionType(guideGoalType);
           /*int b=usersMapper.editUser(users);*/
            toJson.setObject(guideGoalType);
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    @Override
    public ToJson<GuideGoalType> addSupervisionType(HttpServletRequest request, GuideGoalType guideGoalType){
        ToJson<GuideGoalType> toJson=new ToJson<GuideGoalType>(1, "error");
        try{
            int a= guideGoalTypeMapper.addSupervisionType(guideGoalType);
            if(a>0){
                toJson.setObject(guideGoalType);
                toJson.setMsg("ok");
                toJson.setFlag(0);
            }else {
                toJson.setMsg("保存失败");
                throw  new Exception();
            }
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    @Override
    public ToJson<GuideGoalType> deleteSupervisionTypeBySid(Integer sid){
        ToJson<GuideGoalType> toJson=new ToJson<GuideGoalType>( 1,"error");
        try{
            guideGoalTypeMapper.deleteSupervisionTypeBySid(sid);
            if(sid!=0){
                toJson.setMsg("ok");
            }else {
                toJson.setMsg("err");
            }
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
            toJson.setFlag(1);
        }
        return toJson;
    }

    @Override
    public ToJson<GuideGoalType> getSupervisionTypeList(GuideGoalType guideGoalType, HttpServletRequest request, Integer page, Integer pageSize, Boolean useFlag){
        ToJson<GuideGoalType> toJson=new ToJson<GuideGoalType>( 1,"error");
        try{
        	HashMap<String,Object> maps = new HashMap<>();
        	maps.put("page",page);
        	maps.put("pageSize",pageSize);
        	maps.put("useFlag",useFlag);
        	maps.put("supervisionType", guideGoalType);
            List<GuideGoalType> list= guideGoalTypeMapper.getSupervisionTypeList(maps);
            for(int i=0;i<list.size();i++){
				GuideGoalType type=list.get(i);
            	String nameStrings=this.checkAll(type.getUserId());
            	   String[] checkStrings=nameStrings.split("\\|");
      		     //数组长度为1时 说明此时角色和用户Id权限为空
				/*String username="";
				if (i>1||i==0) {
					if(type.getUserId()!=null&&!"".equals(type.getUserId())){
						String userIds = type.getUserId();
						if (userIds.contains("||")) {
							userIds=userIds.substring(2,userIds.length());
						}
						String[] split = userIds.split(",");
						if (split.length > 0) {
							for (String s:split) {
								String name = usersMapper.getUsernameByUserId(s);
								if (name != null) {
									username+=name+",";
								}

							}
						}
					}
					type.setUserName(username);
				}*/

      		   if(checkStrings.length==1){
					type.setDeptName(checkStrings[0]);
					type.setUserPrivName("");
					type.setUserName("");
      		   		}
      		     //数组长度为2时 说明此时角色和用户Id权限为空
      		   if(checkStrings.length==2){
      			 type.setDeptName(checkStrings[0]);
      			type.setUserPrivName(checkStrings[1]);
      			type.setUserName("");
			   }
      		     //数组长度为3时 说明此时部门、角色和用户Id权限都不为空
      		   if(checkStrings.length==3){
      			 type.setDeptName(checkStrings[0]);
      			type.setUserPrivName(checkStrings[1]);
      			type.setUserName(checkStrings[2]);
      		   }
				//数组长度为3时 说明此时部门、角色和用户Id权限都不为空
				if(checkStrings.length==4){
					type.setDeptName(checkStrings[0]);
					type.setUserPrivName(checkStrings[1]);
					type.setUserName(checkStrings[2]);
					type.setUserName(checkStrings[3]);
				}
              }
            if(list.size()>0){
				toJson.setObj(list);
				toJson.setTotleNum(guideGoalTypeMapper.getSupervisionTypeListCount(maps));
               toJson.setMsg("ok");
            }else {
                toJson.setMsg("err");
            }
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }


    @Override
	public ToJson<TreeGirdNode> getSupTypeList(HttpServletRequest request) {
		 ToJson<TreeGirdNode> toJson=new ToJson<TreeGirdNode>(1,"error");
	        try{
	        Map<String,Object> map=new HashMap<String, Object>();
	        map.put("userId", request.getSession().getAttribute("userId"));
	        map.put("userPriv", request.getSession().getAttribute("userPriv"));
	        map.put("deptId", request.getSession().getAttribute("deptId"));
	        String userId=(String) map.get("userId");
	        	List<GuideGoalType> list =new LinkedList<GuideGoalType>();
	             list= guideGoalTypeMapper.getSupManageMenu(null);
	            List<GuideGoalType> rootList=new ArrayList<GuideGoalType>();
	            Iterator<GuideGoalType> total=list.iterator();
	            while (total.hasNext()) {
	            	GuideGoalType type = total.next();
	            	String useriD=this.checkAll(type.getUserId());
					type.setUserName(useriD);
					if(type.getParentId()==0||type.getParentId()==null){
						if(type.getUserId()!=null){
							if("admin".equals(userId)){
								rootList.add(type);
								total.remove();
								continue;
							}
							boolean flag=CheckTree.checkAll(type.getUserId(), map);
							if(flag){
								rootList.add(type);
								total.remove();
							}	
						}
					}
				}
				GuideGoalTreeUtil sup=new GuideGoalTreeUtil(rootList, list,map);
	            List<TreeGirdNode>  totalListAdmin=new LinkedList<TreeGirdNode>();
	            	totalListAdmin=sup.getTreeGirdNode();
	                toJson.setObj(totalListAdmin);
	                toJson.setMsg("ok");
	                toJson.setFlag(0);
	        }catch (Exception e){
	            e.printStackTrace();
	            toJson.setMsg(e.getMessage());
	            toJson.setFlag(1);
	        }
	        return toJson;
	}
	
	/**
	 * 
	 * 创建作者:   杨 胜
	 * 创建日期:   2017-4-26 上午10:01:17
	 * 方法介绍:   验证目录树权限公共方法
	 * 参数说明:   @param checkString
	 * 参数说明:   @param map
	 * 参数说明:   @return
	 * @return   boolean
	 */
	public  String checkAll(String checkString){
		StringBuffer sb=new StringBuffer("");
		Map<String,Object> mapParam=new HashMap<String, Object>();
		//"|"转义字符串  所以必须用\\进行转义 因为 而且取出数组长度不确定
	   String[] checkStrings=checkString.split("\\|");
	   if(checkStrings.length==0){
		   return sb.toString();
	   }
	     //数组长度为1时 说明此时角色和用户Id权限为空
	   if(checkStrings.length==1){
		   String  checkDept=checkStrings[0].substring(0,checkStrings[0].length()==0?0:(checkStrings[0].length()-1));
		   if(checkDept!=null&&!"".equals(checkDept)){
		   	//2019-11-19 处理前端选择全体部门传过来的ALL_DEPT参数问题
			   List<String> listd = new ArrayList<>();
			   if("ALL_DEP".equals(checkDept)){
				   listd=departmentMapper.getAllDeptName();
			   }else {
				   checkDept="'"+checkDept.replace(",", "','")+"'";
				   mapParam.put("checkDept", checkDept);
				   listd=departmentMapper.getDeptNames(mapParam);
			   }
//			   checkDept="'"+checkDept.replace(",", "','")+"'";
//			   mapParam.put("checkDept", checkDept);
//			   List<String> listd=departmentMapper.getDeptNames(mapParam);
			   sb.append(this.getString(listd)).append("|");
		   }else{
			   sb.append("").append("|").append("").append("|"); 
		   }

	   }
	     //数组长度为2时 说明此时角色和用户Id权限为空
	   if(checkStrings.length==2){
		   String  checkDept=checkStrings[0].substring(0,checkStrings[0].length()==0?0:(checkStrings[0].length()-1));
		   if(checkDept!=null&&!"".equals(checkDept)){
			   //2019-11-19 处理前端选择全体部门传过来的ALL_DEPT参数问题
			   List<String> listd = new ArrayList<>();
			   if("ALL_DEP".equals(checkDept)){
				   listd=departmentMapper.getAllDeptName();
			   }else {
				   checkDept="'"+checkDept.replace(",", "','")+"'";
				   mapParam.put("checkDept", checkDept);
				   listd=departmentMapper.getDeptNames(mapParam);
			   }
//			   checkDept="'"+checkDept.replace(",", "','")+"'";
//		   mapParam.put("checkDept", checkDept);
//		    List<String> listd=departmentMapper.getDeptNames(mapParam);
		    sb.append(this.getString(listd)).append("|"); 
		   }else{
			   sb.append("").append("|"); 
		   }
		   String checkUserPriv=checkStrings[1].substring(0,checkStrings[1].length()==0?0:(checkStrings[1].length()-1));
		   if(checkUserPriv!=null&&!"".equals(checkUserPriv)){
			   checkUserPriv="'"+checkUserPriv.replace(",", "','")+"'";
		   mapParam.put("checkUserPriv", checkUserPriv);
		   List<String> listup=userPrivMapper.getUserPNames(mapParam);
		  
		   sb.append(this.getString(listup)).append("|");
		    }else{
				 sb.append("").append("|"); 
			  }
	   }
	     //数组长度为3时 说明此时部门、角色和用户Id权限都不为空
	   if(checkStrings.length==3){
		   String  checkDept=checkStrings[0].substring(0,checkStrings[0].length()==0?0:(checkStrings[0].length()-1));
		   if(checkDept!=null&&!"".equals(checkDept)){
			   //2019-11-19 处理前端选择全体部门传过来的ALL_DEPT参数问题
			   List<String> listd = new ArrayList<>();
			   if("ALL_DEP".equals(checkDept)){
				   listd=departmentMapper.getAllDeptName();
			   }else {
				   checkDept="'"+checkDept.replace(",", "','")+"'";
				   mapParam.put("checkDept", checkDept);
				   listd=departmentMapper.getDeptNames(mapParam);
			   }
//			   checkDept="'"+checkDept.replace(",", "','")+"'";
//		    mapParam.put("checkDept", checkDept);
//		    List<String> listd=departmentMapper.getDeptNames(mapParam);
		    sb.append(this.getString(listd)).append("|"); 
		   }else{
			   sb.append("").append("|"); 
		   }
		   String checkUserPriv=checkStrings[1].substring(0,checkStrings[1].length()==0?0:(checkStrings[1].length()-1));
		   if(checkUserPriv!=null&&!"".equals(checkUserPriv)){
		  /* 	checkUserPriv="'"+checkUserPriv.replace("'", "")+"'";*/
		   mapParam.put("checkUserPriv", checkUserPriv);
		   List<String> listup=userPrivMapper.getUserPNames(mapParam);
		   for(String s:listup){
			   sb.append(s).append(",");
		   }
		  /* sb.append(this.getString(listup)).append("|");*/
		    }else{
				 sb.append("").append("|"); 
		   }
		   String  checkUserId=checkStrings[2].substring(0,checkStrings[2].length()==0?0:(checkStrings[2].length()-1));
		   if(checkUserId!=null&&!"".equals(checkUserId)){
		   checkUserId="'"+checkUserId.replace(",", "','")+"'";
		   mapParam.put("checkUserId", checkUserId);
		   List<String> listCheckUserId=usersMapper.getUserNames(mapParam);
		     sb.append("|");
		     sb.append(this.getString(listCheckUserId));
		   }else{
				sb.append(""); 
		}
	   }
	return sb.toString();
	}
	
	 public String getString( List<String> Strings){
		 StringBuffer sb=new StringBuffer("");
		 if(Strings==null){
			 return "";
		 }
		 for(String s:Strings){
			 sb.append(s);
			 sb.append(",");
		 }
		return sb.toString();
	}

	@Override
	public ToJson<GuideGoalType> getSupNameSelect(HttpServletRequest request, GuideGoalType guideGoalType){
		Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);

		Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);

	 	ToJson<GuideGoalType> toJson=new ToJson<GuideGoalType>(1,"error");
	 	try{
	 		Map map=new HashMap();
	 		map.put("userId",user.getUserId());
	 		map.put("userPriv",user.getUserPriv());
	 		map.put("deptId",user.getDeptId());

	 		List<GuideGoalType> list= guideGoalTypeMapper.getSupNameSelect(map);
	 		if(list.size()>0){
	 			toJson.setObj(list);
	 			toJson.setMsg("ok");
			}else {
	 			toJson.setMsg("空");
			}
			toJson.setFlag(0);
		}catch (Exception e){
	 		e.printStackTrace();
	 		toJson.setMsg(e.getMessage());
		}
		return toJson;
	}
}
